"""
histore database
"""

from sqlobject import *

from path import path

DB_NAME = 'db'


class Record( SQLObject ):

    time    = DateTimeCol( default= None )
    endtime = DateTimeCol( default= None )
    
    title   = UnicodeCol( default= None )
    value   = UnicodeCol( default= None )
    data    = PickleCol( default= None )
    
    tags    = RelatedJoin('Tag')



class Tag( SQLObject ):
    
    name    = UnicodeCol( alternateID= True, length= 20 )
    
    items   = RelatedJoin('Record')



def create():
    Record.createTable()
    Tag.createTable()

def export():
    output_path = path(__file__).dirname() / ( DB_NAME + '.txt' )
    import codecs
    f = codecs.open( output_path, 'w', 'utf-8' )
    br = '\r\n'
    for r in Record.select():
        f.write( '-' + br )
        keys = 'time','endtime','title','value','data'
        for k in keys:
            v = getattr(r,k)
            if v:
                f.write('  %s: %s' % (k,v) + br )
        tags = [ t.name for t in r.tags ]
        f.write('  tags: [%s]' % ', '.join(tags) + br )
    f.close()
    
"""
from datetime import datetime
import histore.db as db
db.create()
"""


"""
procedure addRec( tag in varchar2, time in date, text  in varchar2 ) is
cnt number;
begin

select count(1)
into cnt
from tags t
where t.name=tag;

if cnt=0 then 
insert into Tag(name) values (name);
end if;

insert into Record values (tag,time,text);

commit;

end;



addRecord( 'link', 'txt', time=now(), text='lalala' )
"""

def addRecord( *tags, **kwargs ):
    # Check tags
    record = Record( **kwargs )
    def getTag( name ):
        try:    return Tag.byName( name )
        except: return Tag( name= name )
    map( record.addTag, map( getTag, tags ) )
    return record


    




def main():
    db_path = path(__file__).dirname() / DB_NAME
    connection_string = 'sqlite:/' + str(db_path).replace('\\','/').replace(':','|',1)
    connection_string += '?debug=1'
    print 'connection_string:', connection_string
    connection = connectionForURI( connection_string )
    print 'connection:', connection
    sqlhub.processConnection = connection


main()

